<template>
  <el-container>
    <el-card shadow="always" class="cardBlock">
      <el-form :model="form" ref="form" label-width="130px" :rules="rules" style="width: 800px">

        <el-form-item label="套餐类型" prop="dictMealType">
          <el-radio-group v-model="form.dictMealType" @change="changeMealType" :disabled="disabled">
            <el-radio v-for="item in roadItem.list" :key="item.value" :label="item.type">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="套餐名称" prop="mealName">
          <el-input v-model="form.mealName" placeholder="请输入套餐名称" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item :label="form.dictMealType == 'RELIEVE_LIMIT'?'解封流量阈值('+form.mealSpecUnit+')':'流量'" prop="mealSpec">
          <el-input placeholder="流量" v-model="form.mealSpec" maxlength="7" class="input-with-select" style="width: 300px;">
            <el-select style="width: 80px" v-model="form.mealSpecUnit" slot="append" placeholder="单位">
              <el-option label="MB" value="MB"></el-option>
              <el-option label="GB" value="GB"></el-option>
            </el-select>
          </el-input>
        </el-form-item>
        <el-form-item label="有效期(月)" prop="terOfValidity1" v-if="roadItem.unit=='MONTH'&&form.dictMealType=='SETMEAL_BASE'">
          <el-input v-model="form.terOfValidity1" maxlength="2" style="width: 300px;">
            <template slot="append">月</template>
          </el-input>
        </el-form-item>
        <el-form-item label="有效期(月)" prop="terOfValidity1" v-if="roadItem.label=='SUPERPOSITION_MONTH'&&form.dictMealType=='SETMEAL_ADD_OIL'">
          <el-input v-model="form.terOfValidity1" maxlength="2" style="width: 300px;">
            <template slot="append">月</template>
          </el-input>
        </el-form-item>
        <el-form-item label="有效期(天)" prop="terOfValidity2" v-if="roadItem.unit=='DAY'&&headName!='LIMIT_SPEED_DAY_PLUS'&&form.dictMealType=='SETMEAL_BASE'">
          <el-input v-model="form.terOfValidity2" maxlength="3" style="width: 300px;">
            <template slot="append">天</template>
          </el-input>
        </el-form-item>
        <el-form-item label="有效期(天)" prop="terOfValidity2" v-if="roadItem.label=='SUPERPOSITION_DAY'&&form.dictMealType=='SETMEAL_ADD_OIL'">
          <el-input v-model="form.terOfValidity2" maxlength="3" style="width: 300px;">
            <template slot="append">天</template>
          </el-input>
        </el-form-item>
        <el-form-item label="有效期(天)" prop="terOfValidity3" v-if="headName=='LIMIT_SPEED_DAY_PLUS'&&form.dictMealType=='SETMEAL_BASE'">
          <el-input v-model="form.terOfValidity3" maxlength="4" style="width: 300px;">
            <template slot="append">天</template>
          </el-input>
        </el-form-item>
        <el-form-item label="有效期" prop="terOfValidity4" v-if="roadItem.unit==''||form.dictMealType=='TRY_MEAL'">
          <el-input placeholder="有效期" v-model="form.terOfValidity4" class="input-with-select" style="width: 300px;">
            <el-select style="width: 80px" v-model="form.dictTerOfValidity" slot="append" placeholder="单位">
              <el-option label="月" value="MONTH"></el-option>
              <el-option label="天" value="DAY"></el-option>
            </el-select>
          </el-input>
        </el-form-item>
        <el-form-item label="官方售价(元)" prop="officialPrice">
          <el-input v-model="form.officialPrice" maxlength="7" style="width: 300px">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="代理售价上限(元)" prop="ceilingPrice">
          <el-input v-model="form.ceilingPrice" maxlength="7" style="width: 300px">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="OEM成本价" prop="oemCostPrice">
          <el-input v-model="form.oemCostPrice" maxlength="7" style="width: 300px">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="权限值" prop="cardFlowImaginary" v-if="headName!=='TONGYONG_HEAD'">
          <el-input-number v-model="form.cardFlowImaginary" :precision="2" :step="0.1" :max="999" style="width: 200px;"></el-input-number>
        </el-form-item>
        <el-form-item label="上游套餐编号" prop="thirdId" v-if="headName=='TONGYONG_HEAD'">
          <el-input v-model="form.thirdId" style="width: 300px;"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="seq">
          <el-input v-model="form.seq" maxlength="4" style="width: 300px;"></el-input>
        </el-form-item>
        <el-form-item label="限制充值次数" prop="num" v-if="form.dictMealType=='TRY_MEAL'">
          <el-input v-model="form.num" style="width: 300px;"></el-input>
        </el-form-item>
        <el-form-item label="是否分期到账" prop="dictDayPayment" v-if="headName==='LIMIT_SPEED_DAY_PLUS'&&form.dictMealType==='SETMEAL_BASE'">
          <el-radio-group v-model="form.dictDayPayment" @change="changeDictDayPayment">
            <el-radio label="YES">是</el-radio>
            <el-radio label="NO">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="到账周期" prop="dictDayNumber" v-if="form.dictDayPayment=='YES'&&form.dictMealType==='SETMEAL_BASE'">
          <el-input v-model="form.dictDayNumber" maxlength="2" placeholder="请填写到账周期数" style="width: 300px" type="Number">
            <template slot="append">期</template>
          </el-input>
        </el-form-item>
        <el-form-item label="是否分月到账" prop="dictMonthlyPayment" v-if="(roadItem.showFormRadio&&form.dictMealType==roadItem.list[0].type&&headName!='LIMIT_SPEED_DAY_PLUS')||(headName=='TONGYONG_HEAD'&&form.dictMealType!='TRY_MEAL'&&headName!='LIMIT_SPEED_DAY_PLUS')">
          <el-radio-group v-model="form.dictMonthlyPayment" @change="changeDictMonthlyPayment">
            <el-radio label="YES">是</el-radio>
            <el-radio label="NO">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否次月生效" prop="dictIsPreStorage" v-if="(roadItem.showFormRadio&&form.dictMealType==roadItem.list[0].type)||(headName=='TONGYONG_HEAD'&&form.dictMealType!='TRY_MEAL')">
          <el-radio-group v-model="form.dictIsPreStorage" @change="changeDictIsPreStorage">
            <el-radio label="YES">是</el-radio>
            <el-radio label="NO">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否连续充值" prop="dictIsTerOfValiditySuper" v-show="(roadItem.showFormRadio&&form.dictMealType==roadItem.list[0].type)||(headName=='TONGYONG_HEAD'&&form.dictMealType!='TRY_MEAL')">
          <el-radio-group v-model="form.dictIsTerOfValiditySuper">
            <el-radio label="C_YES">是</el-radio>
            <el-radio label="C_NO">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="类型" prop="dictOperator" v-if="headName.indexOf('LIMIT') > -1 && form.dictMealType == 'SETMEAL_BASE'">
          <el-radio-group v-model="form.dictOperator" size="small" @change="changCardFact">
            <el-radio label="CHINAMOBILE" border>移动</el-radio>
            <el-radio label="TELECOM" border>电信DCP</el-radio>
            <el-radio label="CMPTELECOM" border>电信CMP</el-radio>
            <el-radio label="UNICOM" border>联通</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="限速条件" v-show="headName.indexOf('LIMIT') > -1 && form.dictMealType == 'SETMEAL_BASE'">
          <el-button type="primary" @click="addspeed" icon="el-icon-plus">添加</el-button>
        </el-form-item>
        <el-row v-for="(speed, index) in form.speeds" :key="speed.key" v-show="headName.indexOf('LIMIT') > -1 && form.dictMealType == 'SETMEAL_BASE'">
          <el-col :span="8">
            <el-form-item
              :label="'限速阈值' + index"
              :prop="'speeds.' + index + '.limitMb'"
              :rules="[{ required: true, message: '阈值不能为空', trigger: 'blur' }]"
            >
              <el-input v-model="speed.limitMb" style="width: 170px" >form.mealSpec?form.mealSpec:speed.limitMb">
                <template slot="append"  >GB</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item
              :label="'限速等级' + index"
              :prop="'speeds.' + index + '.limitSpeed'"
              :rules="{ required: true, message: '等级不能为空', trigger: 'blur' }"
            >
              <el-select v-model="speed.limitSpeed" placeholder="请选择" style="width: 200px">
                <el-option v-for="item in limitList" :label="item.label" :value="item.value" :key="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button type="danger" plain @click.prevent="removeSpeed(speed)">删除</el-button>
          </el-col>
        </el-row>
        <el-form-item porp="ifCheckOnlyRechargeBaseSetmeal" label="是否校验重复订购" v-if="headName=='TONGYONG_HEAD'">
          <el-radio-group v-model="form.ifCheckOnlyRechargeBaseSetmeal">
            <el-radio label="C_YES">是</el-radio>
            <el-radio label="C_NO">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="dictStatus" label="是否立即开启套餐">
          <el-switch
            active-value="C_YES"
            inactive-value="C_NO"
            v-model="form.dictStatus"
            @change="changePackageStatus($event)">
            active-color="#13ce66"
            inactive-color="#999"
          </el-switch>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit('form')">提交</el-button>
          <el-button type="primary" @click="resetForm('form')" plain>重置</el-button>
          <el-row style="color:red">注：更改任何价格都请马上重新设置代理的费率！</el-row>
          <el-row style="color:red" v-if="headName=='TONGYONG_HEAD'">注：通用套餐是否次支持月生效、是否支持连续充值、是否支持分月到账请参考上游套餐，以上游套餐为准！</el-row>
          <el-row style="color:red" v-if="headName=='TONGYONG_HEAD'">注：如果重复订购为是，会校验该卡是否已经充值了本月生效或者上个月次月生效的订单，如果有会提示用户“已经充值过相同类型的套餐！订购失败！”，仅对三方卡，且月结套餐有效。</el-row>
        </el-form-item>
      </el-form>
    </el-card>
  </el-container>
</template>
<script>
import {getSetMeal, packageconserve} from '../../../api/getData'
import {is2PoinFloat, isNumber} from '../../../utils/validate'

export default {
  data() {

    const validateNum = (rule, value, callback) => {
      if (!is2PoinFloat(parseFloat(value))) {
        callback(new Error('请输入非负数，且保留小数点后两位'))
      } else {
        callback()
      }
    };
    const validateSeq = (rule, value, callback) => {
      if (!is2PoinFloat(value)) {
        return callback(new Error('请输入正整数'))
      }
      else {
        if(value>rule.max||value<rule.min){
          return callback(new Error(`最小值${rule.min}，最大值${rule.max}`))
        }
        callback()
      }
    };

    const validateFlow = (rule, value, callback) => {

      if (!is2PoinFloat(value)) {
        return callback(new Error('请输入正整数'))
      } else {
        if(value<1){
          return callback(new Error(`最小值1`))
        }
        // else{
        //   if(this.form.mealSpecUnit=='GB'){
        //     if(value>9999){
        //       return callback(new Error(`最大值9999`))
        //     }
        //     else{
        //       callback()
        //     }
        //   }
        //   else if(this.form.mealSpecUnit=='MB'){
        //     if(value>10238976){
        //       return callback(new Error(`最大值10238976`))
        //     }
        //     else{
        //
        //     }
        //   }
        // }
        callback()
      }
    };

    const validateDate = (rule, value, callback) => {
      if (!isNumber(value)) {
        return callback(new Error('请输入正整数'))
      } else {
        if (this.form.dictTerOfValidity == 'DAY') {
          if ((value > 360 || value < 1) && this.form.dictMealType == 'TRY_MEAL') {
            return callback(new Error(`最大值360，最小值1`))
          } else if ((value > 720 || value < 7) && this.roadItem.label=='SUPERPOSITION_DAY'&&this.form.dictMealType=='SETMEAL_ADD_OIL') {
            return callback(new Error(`最大值365，最小值7`))
          } else if ((value > 720 || value < 7) && this.roadItem.unit=='DAY'&&this.headName!='LIMIT_SPEED_DAY_PLUS'&&this.form.dictMealType=='SETMEAL_BASE') {
            return callback(new Error(`最大值365，最小值7`))
          } else if ((value > 1097 || value < 7) && this.headName=='LIMIT_SPEED_DAY_PLUS'&&this.form.dictMealType=='SETMEAL_BASE') {
            return callback(new Error(`最大值1097，最小值7`))
          } else {
            callback()
          }
        }
        if (this.form.dictTerOfValidity == 'MONTH') {
          if (value > 70 || value < 1) {
            return callback(new Error(`最大值70，最小值1`))
          }
        }
        callback()
      }
    };
    // const eqValidata = (rule, value, callback) => {
    //   if (!value) {
    //     return callback(new Error('请输入有效期'));
    //   }
    //   let reg = /^\d{1,3}$/;
    //   if (rule && rule.min) {
    //     if (reg.test(value)) {
    //       if (value < rule.min || value > rule.max) {
    //         return callback(new Error('您修改您输入的有效期，最小值' + rule.min + '，最大值' + rule.max));
    //       } else {
    //         callback()
    //       }
    //     } else {
    //       return callback(new Error('有效期格式错误'));
    //     }
    //   } else {
    //     if (this.form.dictTerOfValidity === 'DAY') {
    //       if (value < 7 || value > 365) {
    //         return callback(new Error('您修改您输入的有效期，最小值7，最大值365'));
    //       } else {
    //         callback()
    //       }
    //     } else if (this.form.dictTerOfValidity === 'MONTH') {
    //       if (value < 1 || value > 36) {
    //         return callback(new Error('您修改您输入的有效期，最小值1，最大值36'));
    //       } else {
    //         callback()
    //       }
    //     }
    //   }
    // }
    const numberValidata = (rule, value, callback) => {
      let reg = /^[0-9]+(\.[0-9]{1,2})?$/;
      if (!value || !reg.test(value) || value < rule.min || value > rule.max) {
        return callback(new Error('您修改您输入的金额，最小值' + rule.min + '，最大值' + rule.max));
      } else {
        callback()
      }
    };
    const validateDayNumber = (rule, value, callback) => {
      if (value < 1 || value > 36) {
        return callback(new Error('您修改您输入的数值，最小值1，最大值36'));
      } else {
        callback()
      }
    };
    const checkLimitmb = (rule, value, callback) => {
      if (this.form.mealSpec * 1 - value * 1 < 0) {
        callback(new Error('请不要超过总流量'))
      } else {
        callback()
      }
    };
    return {
      road: [],       //套餐类型列表
      roadItem: {},   //套餐类型对象
      id: '',         //套餐小类id
      headId: '',     //套餐大类id
      headName: '',   //套餐大类名称
      disabled: false,//套餐类型是否disabled
      form: {
        mealType: '',                       //套餐类型
        dictMealType: '',                   //套餐类型（后台）
        mealName: '',                       //套餐名称
        dictDayPayment: 'NO',               //是否分期到账
        dictMonthlyPayment: 'NO',           //是否分月到账
        dictIsPreStorage: 'NO',             //是否次月生效
        dictIsTerOfValiditySuper: 'C_NO',   //是否连续充值
        thirdId: '',                        //上游套餐编号
        seq: '',                            //排序
        cardFlowImaginary: 1,               //权限值
        oemCostPrice: '',                   //OEM成本价
        ceilingPrice: '',                   //代理售价上限
        officialPrice: '',                  //官方售价
        terOfValidity1: '',                 //有效期(月)
        terOfValidity2: '',                 //有效期(天)
        terOfValidity3: '',                 //有效期(天)
        terOfValidity4: '',                 //有效期(天)
        dictTerOfValidity: '',              //有效期单位
        mealSpec: '',                       //流量
        mealSpecUnit: 'GB',                 //流量(单位)
        dictOperator: '',                   //类型
        speeds: [],                         //限速列表
        num: '',                            //限制充值次数
        dictDayNumber: 1,                   //到账周期
        ifCheckOnlyRechargeBaseSetmeal: 'C_NO',//是否校验重复订购
        dictStatus: 'C_NO',                 //套餐状态
      },
      limitList: [],                        //限速列表
      rules: {
        dictOperator: [
          {required: true, message: '请选择卡类型', trigger: 'change'}
        ],
        mealName: [
          {required: true, message: '请输入套餐名称', trigger: 'blur'},
          {min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur'}
        ],
        mealSpec: [
          {required: true, message: '请输入流量', trigger: 'blur'},
          {validator: validateFlow, trigger: 'blur'}
        ],
        terOfValidity1: [
          {required: true, message: '请输入有效期', trigger: 'blur'},
          {validator: validateDate, min: 1, max: 36, trigger: 'blur'},
        ],
        terOfValidity2: [
          {required: true, message: '请输入有效期', trigger: 'blur'},
          {validator: validateDate,  trigger: 'blur'}
        ],
        terOfValidity3: [
          {required: true, message: '请输入有效期', trigger: 'blur'},
          {validator: validateDate, trigger: 'blur'}
        ],
        terOfValidity4: [
          {required: true, message: '请输入有效期', trigger: 'blur'},
          {validator: validateDate, trigger: 'blur'}
        ],

        officialPrice: [
          {required: true, message: '请输入官方售价', trigger: 'blur'},
          {validator: validateNum, min: 0.1, max: 5000, trigger: 'blur'}
        ],
        ceilingPrice: [
          {required: true, message: '请输入代理售价上限', trigger: 'blur'},
          {validator: validateNum, min: 0.1, max: 5000, trigger: 'blur'}
        ],
        oemCostPrice: [
          {required: true, message: '请输入代OEM成本价', trigger: 'blur'},
          {validator: validateNum, min: 0.1, max: 5000, trigger: 'blur'}
        ],
        cardFlowImaginary: [
          {required: true, message: '请输入权限值', trigger: 'change'},
          {pattern: /^\d+(\.\d{0,2})?$/, message: '请填写正确的权限值,保留两位小数'}
        ],
        seq: [
          {required: true, message: '请输入排序序号', trigger: 'blur'},
          {validator: validateSeq, min: 1, max: 5000, trigger: 'blur'}
        ],
        dictMonthlyPayment: [//是否到月分账
          {required: true, message: '请选择是否分月到账', trigger: 'blur'},
        ],
        dictDayNumber: [//是否分期到账--是 必填周期天数
          {required: true, message: '请填写分期到账周期', trigger: 'blur'},
          {pattern: /^[1-9]\d*$/, message: '到账周期必须为整数', trigger: 'blur'},
          {validator: validateDayNumber, message: '到账周期最小值1，最大值24', trigger: 'blur'}
        ],
        dictIsTerOfValiditySuper: [//是否连续充值
          {required: true, message: '请选择是否连续充值', trigger: 'blur'},
        ],
        thirdId: [
          {required: true, message: '请输入上游编号', trigger: 'blur'},
        ],
        limitMb: [
          {required: true, message: '请输入限速阈值', trigger: 'blur'},
          {validator: numberValidata, min: 1, max: 9999999, trigger: 'blur'},
          {validator: checkLimitmb, trigger: 'blur'}
        ],
        limitSpeed: [
          {required: true, message: '请选择限速等级', trigger: 'blur'},
        ],
        num: [//
          {required: true, message: '请填写限制充值次数', trigger: 'blur'},
          {pattern: /^[1-9]\d*$/, message: '充值次数必须为整数', trigger: 'blur'}
        ],

      }
    }
  },
  async mounted() {
    this.road = [
      {label: 'BASE_MONTH', list: [{value: '1', label: '基础包', type: 'SETMEAL_BASE'}, {value: '2', label: '加油包', type: 'SETMEAL_ADD_OIL'}, {value: '5', label: '试用包', type: 'TRY_MEAL'}], showFormRadio: true, unit: 'MONTH'},
      {label: 'BASE_DAY', list: [{value: '1', label: '基础套餐', type: 'SETMEAL_BASE'}, {value: '2', label: '加油包', type: 'SETMEAL_ADD_OIL'}, {value: '5', label: '试用包', type: 'TRY_MEAL'}], showFormRadio: false, unit: 'DAY'},
      {label: 'SUPERPOSITION_MONTH', list: [{value: '2', label: '加油包', type: 'SETMEAL_ADD_OIL'}, {value: '5', label: '试用包', type: 'TRY_MEAL'}], showFormRadio: true, unit: 'MONTH'},
      {label: 'SUPERPOSITION_DAY', list: [{value: '2', label: '加油包', type: 'SETMEAL_ADD_OIL'}, {value: '5', label: '试用包', type: 'TRY_MEAL'}], showFormRadio: false, unit: 'DAY'},
      {label: 'LIMIT_SPEED', list: [{value: '1', label: '基础包', type: 'SETMEAL_BASE'}, {value: '2', label: '加油包', type: 'SETMEAL_ADD_OIL'}, {value: '3', label: '解封包', type: 'RELIEVE_LIMIT'}, {value: '5', label: '试用包', type: 'TRY_MEAL'}], showFormRadio: true, unit: 'MONTH'},
      {label: 'LIMIT_SPEED_DAY', list: [{value: '1', label: '基础包', type: 'SETMEAL_BASE'}, {value: '2', label: '加油包', type: 'SETMEAL_ADD_OIL'}, {value: '3', label: '解封包', type: 'RELIEVE_LIMIT'}, {value: '5', label: '试用包', type: 'TRY_MEAL'}], showFormRadio: false, unit: 'DAY'},
      {label: 'LIMIT_SPEED_DAY_PLUS', list: [{value: '1', label: '基础包', type: 'SETMEAL_BASE'}, {value: '2', label: '加油包', type: 'SETMEAL_ADD_OIL'}, {value: '3', label: '解封包', type: 'RELIEVE_LIMIT'}, {value: '5', label: '试用包', type: 'TRY_MEAL'}], showFormRadio: true, unit: 'DAY'},
      {label: 'TONGYONG_HEAD', list: [{value: '1', label: '基础包', type: 'SETMEAL_BASE'}, {value: '2', label: '加油包', type: 'SETMEAL_ADD_OIL'}, {value: '4', label: '通用套餐', type: 'TONGYONG_HEAD'}, {value: '5', label: '试用包', type: 'TRY_MEAL'}], showFormRadio: true, unit: ''},
    ]
    this.id = this.$route.query.id ? this.$route.query.id : '';
    this.headName = this.$route.query.headName;
    this.headId = this.$route.query.headId;
    this.roadItem = this.road.find(item => {
      return item.label == this.headName
    });

    this.form.dictTerOfValidity = this.roadItem.unit;
    this.form.dictMealType = this.headName == 'TONGYONG_HEAD' ? 'TONGYONG_HEAD' : this.roadItem.list[0].type;
    if (this.headName == 'TONGYONG_HEAD') this.form.dictTerOfValidity = 'MONTH';
    this.disabled = this.id ? true : false;
    if (this.id) {
      this.initData();
    }
    this.pagekey = await this.$getPageKey();
  },
  methods: {
    onSubmit(formName) {
      let _this = this;

      this.$refs[formName].validate(valid => {
        console.log(valid)
        if (valid) {
          if (this.form.officialPrice * 1 < this.form.oemCostPrice * 1) {
            this.$message.error("官方售价不能低于OEM成本价！");
            return;
          }
          if (this.form.ceilingPrice * 1 < this.form.oemCostPrice * 1) {
            this.$message.error("代理设置的上限价格不能低于OEM成本价！");
            return;
          }
          if (this.form.ceilingPrice * 1 < this.form.officialPrice * 1) {
            this.$message.error("代理设置的上限价格不能低于官方售价！");
            return;
          }
          this.loading = true;
          let dictIsPreStorage = 'NO';            //是否次月生效
          let dictMonthlyPayment = 'NO';          //是否分月到账
          let dictIsTerOfValiditySuper = 'C_NO';  //是否连续充值
          let cycle = '';                         //高级达量限速套餐（日）使用的周期数
          if (this.roadItem.showFormRadio) {
            dictIsPreStorage = this.form.dictIsPreStorage;
            dictMonthlyPayment = this.form.dictMonthlyPayment;
            dictIsTerOfValiditySuper = this.form.dictIsTerOfValiditySuper;
          }
          if (this.headName === "LIMIT_SPEED_DAY_PLUS") {
            dictMonthlyPayment = this.form.dictDayPayment;
            cycle = this.form.dictMealType == 'SETMEAL_BASE' && this.form.dictDayPayment == 'YES' ? this.form.dictDayNumber : '';
          }
          let terOfValidity = '';                 //有效期时间
          let dictTerOfValidity = '';             //有效期单位 月 or 日
          if (this.roadItem.unit == 'MONTH') {
            dictTerOfValidity = 'MONTH'
            terOfValidity = this.form.terOfValidity1
          }

          if (this.roadItem.unit == 'DAY') {
            dictTerOfValidity = 'DAY';
            terOfValidity = this.form.terOfValidity2;
            if (this.roadItem.label == 'LIMIT_SPEED_DAY_PLUS') {
              terOfValidity = this.form.terOfValidity3;
            }
          }
          if (this.roadItem.unit == '' || this.form.dictMealType == 'TRY_MEAL') {
            dictTerOfValidity = this.form.dictTerOfValidity
            terOfValidity = this.form.terOfValidity4
          }
          let dictOperator = '';                //达量限速卡类型
          let speeds = [];                      //限速条件
          let mealSpec = this.form.mealSpec;    //流量值

          mealSpec = this.form.mealSpecUnit === 'GB' ? mealSpec * 1024 : mealSpec;
          if (this.limitList.length > 0) {
            dictOperator = this.form.dictOperator;
            if (this.form.speeds) {
              for (let item of this.form.speeds) {
                let obj = {};
                obj.limitMb = this.form.mealSpecUnit == 'GB' ? item.limitMb * 1024 : item.limitMb;
                obj.limitSpeed = item.limitSpeed;
                speeds.push(obj);
              }
            }
          }
          let ifCheckOnlyRechargeBaseSetmeal = this.headName =='TONGYONG_HEAD'?this.form.ifCheckOnlyRechargeBaseSetmeal: '';
          let cardFlowImaginary = this.headName !== 'TONGYONG_HEAD' ? this.form.cardFlowImaginary : '';//权限值
          let rechargeNum = this.form.dictMealType == 'TRY_MEAL' ? this.form.num : '';
          let form = {
            dictMealType: this.form.dictMealType,				            //套餐类型
            dictSetMealGroupType: this.headName,                		//套餐大类
            headId: this.headId,								                    //套餐大类id
            id: this.id,									                          //套餐id
            mealName: this.form.mealName,								            //套餐名称
            mealSpec,         								                      //流量
            officialPrice: this.form.officialPrice,						      //官方售价(元)
            ceilingPrice: this.form.ceilingPrice,							      //代理售价上限(元)
            oemCostPrice: this.form.oemCostPrice,							      //OEM成本价
            seq: this.form.seq,									                    //排序
            cardFlowImaginary,                  						        //权限值 / 虚值
            dictIsPreStorage,                                       //是否次月生效
            terOfValidity,						                              //有效期
            dictTerOfValidity,                  				            //有效期类型 月 / 日
            dictMonthlyPayment,                                     //是否分月到账
            speeds: JSON.stringify(speeds),                         //限速条件
            dictOperator,                                           //运营商
            dictIsTerOfValiditySuper,                               //连续充值
            thirdId: this.form.thirdId,                             //上游套餐编号
            cycle,                                                  //周期数（高级达量限速套餐日专用套餐）
            rechargeNum,                                            //限制充值次数
            ifCheckOnlyRechargeBaseSetmeal,                         //是否校验重复订购
            dictStatus: this.form.dictStatus,                       //套餐开启 or 隐藏
          };
          packageconserve(form, {pagekey: this.pagekey});
          this.$message.success("套餐初始化中，请稍后查看");
          this.loading = false;
          setTimeout(() => {
            this.$router.back(-1);
          }, 100);
        }
      })
    },
    async initData() {
      let s = await getSetMeal({id: this.id});
      if (s._result) {
        this.form.dictMealType = s.data.dictMealType;//套餐类型
        this.form.mealName = s.data.mealName;
        this.form.mealSpec = s.data.mealSpec >= 1024 ? parseFloat(s.data.mealSpec / 1024).toFixed(2) : s.data.mealSpec;
        this.form.mealSpecUnit = s.data.mealSpec >= 1024 ? 'GB' : 'MB';
        this.form.officialPrice = s.data.officialPrice;       //官方售价(元)
        this.form.ceilingPrice = s.data.ceilingPrice;         //代理售价上限(元)
        this.form.oemCostPrice = s.data.oemCostPrice;         //OEM成本价
        this.form.cardFlowImaginary = s.data.cardFlowImaginary;//权限值
        this.form.seq = s.data.seq;                           //排序
        this.form.dictOperator = s.data.dictOperator;         //达量限速卡类型
        this.form.thirdId = s.data.thirdId;                   //上游套餐编号
        this.form.dictIsPreStorage = s.data.dictIsPreStorage == 'YES' ? 'YES' : 'NO';                               //是否次月生效
        this.form.dictMonthlyPayment = s.data.dictMonthlyPayment == 'YES' ? 'YES' : 'NO';                           //是否分月到账
        this.form.dictIsTerOfValiditySuper = s.data.dictIsTerOfValiditySuper == 'C_YES' ? 'C_YES' : 'C_NO';         //是否连续充值
        this.form.dictDayNumber = "";                         //分期数
        this.form.dictTerOfValidity = s.data.dictTerOfValidity;  //有效期单位
        this.form.dictStatus = s.data.dictStatus=='C_YES'?'C_YES':'C_NO';
        console.log('this.form.dictStatus='+this.form.dictStatus)
        if (this.roadItem.unit == 'MONTH' && this.form.dictMealType != 'TRY_MEAL') {
          this.form.terOfValidity1 = s.data.terOfValidity + '';    //有效期(月)
        }

        if ((this.roadItem.unit=='DAY'&&this.headName!='LIMIT_SPEED_DAY_PLUS'&&this.form.dictMealType=='SETMEAL_BASE') || (this.roadItem.label=='SUPERPOSITION_DAY'&&this.form.dictMealType=='SETMEAL_ADD_OIL')) {
          this.form.terOfValidity2 = s.data.terOfValidity + '';    //有效期(日)
        }
        if (this.headName=='LIMIT_SPEED_DAY_PLUS'&&this.form.dictMealType=='SETMEAL_BASE' ) {
          this.form.terOfValidity3 = s.data.terOfValidity + '';    //有效期(日)
        }
        if (this.roadItem.unit == '' || this.form.dictMealType == 'TRY_MEAL') {
          this.form.terOfValidity4 = s.data.terOfValidity + '';    //有效期(日/月)
        }
        if (this.headName == "LIMIT_SPEED_DAY_PLUS") {
          this.form.dictMonthlyPayment = "NO";
          this.form.dictDayPayment = s.data.dictMonthlyPayment == 'YES' ? 'YES' : 'NO';                                   //是否分期到账
          this.form.dictDayNumber = s.data.cycle ? s.data.cycle : '';
        }
        this.form.num = s.data.rechargeNum;
        this.form.ifCheckOnlyRechargeBaseSetmeal = s.data.ifCheckOnlyRechargeBaseSetmeal;

        if(this.headName=='TONGYONG_HEAD'){
          this.form.ifCheckOnlyRechargeBaseSetmeal = s.data.ifCheckOnlyRechargeBaseSetmeal?s.data.ifCheckOnlyRechargeBaseSetmeal:'C_NO';
        }
        let arr = JSON.parse(s.data.speeds);
        if (arr && arr.length > 0) {
          arr.forEach((item, index) => {
            if (item.limitMb >= 1024 || this.form.mealSpecUnit === 'GB') {
              item.limitMb = parseFloat(item.limitMb / 1024).toFixed(2);
            }
            let obj = {
              limitMb: item.limitMb,
              limitSpeed: item.limitSpeed,
            }
            this.form.speeds.push(obj)
          });
          if (arr.length == 0) {
            this.addspeed()
          }
        }
        this.changeMealType(this.form.dictMealType);
        if (this.headName.indexOf('LIMIT') == 0) this.getLimitList(s.data.dictOperator)
        console.log(this.form)
      }
    },
    resetForm(formName) {
      let dictMealType = this.id?this.form.dictMealType:this.roadItem.list[0].type;
      this.form.dictMealType = dictMealType;
      this.form.mealName = '';
      this.form.speeds = [];
      this.form.dictMonthlyPayment = 'NO';
      this.form.dictDayPayment = 'NO';
      this.form.dictIsPreStorage = 'NO';
      this.form.dictIsTerOfValiditySuper = 'C_NO';
      this.form.cardFlowImaginary = '1';
      this.form.oemCostPrice = '';
      this.form.terOfValidity1 = '';
      this.form.terOfValidity2 = '';
      this.form.terOfValidity3 = '';
      this.form.terOfValidity4 = '';
      this.form.thirdId = '';
      this.form.seq = '';
      this.form.oemCostPrice = '';
      this.form.ceilingPrice = '';
      this.form.officialPrice = '';
      this.form.mealSpec = '';
      this.form.mealSpecUnit = 'GB';
      this.form.dictOperator = '';
      this.form.speeds = [];
      this.form.num = null;
      this.form.dictDayNumber = null;
      // this.form = {
      //   dictMealType: dictMealType,         //套餐类型（后台）
      //   mealName: '',                       //套餐名称
      //   dictDayPayment: 'NO',               //是否分期到账
      //   dictMonthlyPayment: 'NO',           //是否分月到账
      //   dictIsPreStorage: 'NO',             //是否次月生效
      //   dictIsTerOfValiditySuper: 'C_NO',   //是否连续充值
      //   thirdId: '',                        //上游套餐编号
      //   seq: '',                            //排序
      //   cardFlowImaginary: 1,               //权限值
      //   oemCostPrice: '',                   //OEM成本价
      //   ceilingPrice: '',                   //代理售价上限
      //   officialPrice: '',                  //官方售价
      //   terOfValidity1: '',                 //有效期(月)
      //   terOfValidity2: '',                 //有效期(天)
      //   terOfValidity3: '',                 //有效期(天)
      //   terOfValidity4: '',                 //有效期(天)
      //   dictTerOfValidity: '',              //有效期单位
      //   mealSpec: '',                       //流量
      //   mealSpecUnit: 'GB',                 //流量(单位)
      //   dictOperator: '',                   //类型
      //   speeds: [],                         //限速列表
      //   num: '',                            //限制充值次数
      //   dictDayNumber: 1,                   //到账周期
      // }
    },
    changePackageStatus(val){
      console.log(val)
      this.form.dictStatus = val;
    },
    changeMealType(val) {
      this.form.dictMealType = val;
      if (!this.id) {
        this.form.dictMonthlyPayment = 'NO';
        this.form.dictIsPreStorage = 'NO';
        this.form.dictIsTerOfValiditySuper = 'C_NO';
      }
    },
    changeDictMonthlyPayment(val) {
      this.form.dictMonthlyPayment = val;
      if (val == 'YES') this.form.dictIsPreStorage = 'NO';
    },
    changeDictIsPreStorage(val) {
      this.form.dictIsPreStorage = val;
      if (val == 'YES') {
        this.form.dictMonthlyPayment = 'NO';
        this.form.dictDayPayment = 'NO';
      }
    },

    changCardFact(val) {
      this.form.dictOperator = val;
      this.form.speeds = [
        {limitMb: '', limitSpeed: ''}
      ]
      this.getLimitList(val)
    },
    getLimitList(val) {
      this.limitList = []
      if (val == 'CHINAMOBILE') {
        this.limitList = [
          {value: '91:APN-AMBR=2Mbps', label: '91:APN-AMBR=2Mbps'},
          {value: '92:APN-AMBR=1Mbps', label: '92:APN-AMBR=1Mbps'},
          {value: '93:APN-AMBR=512Kbps', label: '93:APN-AMBR=512Kbps'},
          {value: '94:APN-AMBR=128Kbps', label: '94:APN-AMBR=128Kbps'},
        ]
      } else if (val == 'TELECOM') {
        for (let i = 1; i < 16; i++) {
          this.limitList.push({value: i, label: i})
        }
      } else if (val == 'CMPTELECOM') {
        this.limitList = [
          {value: '12', label: '1Mbps'},
          {value: '13', label: '3Mbps'},
          {value: '14', label: '5Mbps'},
          {value: '16', label: '10Mbps'},
          {value: '17', label: '20Mbps'},
          {value: '31', label: '不限制'},
        ]
      }else if(val =='UNICOM'){
        this.limitList = [
        {value: '22011447', label: '取消限速'},
        {value: '22011444', label: '取消限速'},
        {value: '22011443', label: '等级2'},
        {value: '22011442', label: '等级3'},
        {value: '22011441', label: '等级4'},
        {value: '22011440', label: '等级5'},
        {value: '22011439', label: '等级6'},
        {value: '22011438', label: '等级7'}
        ]
      }
    },
    addspeed() {
      this.form.speeds.push({
        limitSpeed: '',
        limitMb: '',
      });
    },
    removeSpeed(item) {
      var index = this.form.speeds.indexOf(item)
      if (index !== -1) {
        this.form.speeds.splice(index, 1)
      }
    },
    //切换是否分期到账 此条件与连续充值互斥
    changeDictDayPayment(val) {
      this.form.dictDayPayment = val;
      if (val == 'YES') {
        this.form.dictIsPreStorage = 'NO';
        this.form.dictDayNumber = '';
      }
    },
  }
}
</script>
<style scoped>
.cardBlock {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 50px auto;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  width: 1000px
}
</style>
